import { defineEventHandler, getCookie, readBody, createError } from 'h3';
import scheduler from '../../utils/scheduler.js';

export default defineEventHandler(async (event) => {
  try {
    const userId = getCookie(event, 'userId');
    if (!userId) {
      throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
    }

    const { taskName } = await readBody(event);
    
    if (!taskName) {
      throw createError({ statusCode: 400, statusMessage: 'Task name is required' });
    }

    // 验证任务属于当前用户
    if (!taskName.startsWith(`user_${userId}_`)) {
      throw createError({ statusCode: 403, statusMessage: 'Access denied' });
    }

    const result = scheduler.stopScheduledBackup(taskName);

    return {
      success: result.success,
      message: result.success ? '定时备份任务已停止' : result.message
    };
  } catch (error) {
    console.error('停止定时备份失败:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to stop scheduled backup' });
  }
});
